package com.doubao.user.controller;

import com.doubao.common.result.Result;
import com.doubao.user.dto.request.UserWechatBindRequest;
import com.doubao.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 用户微信绑定控制器
 */
@RestController
@RequestMapping("/user/wechat")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "用户微信绑定", description = "用户微信绑定相关接口")
public class UserWechatController {

    private final UserService userService;

    /**
     * 绑定微信账号
     */
    @PostMapping("/bind")
    @Operation(summary = "绑定微信账号", description = "将用户账号与微信OpenID绑定")
    public Result<Void> bindWechat(@RequestBody(required = false) UserWechatBindRequest requestBody,
                                   @RequestParam(required = false) Long userId,
                                   @RequestParam(required = false) String openid,
                                   @RequestParam(required = false) String unionid,
                                   @RequestParam(required = false) String type) {
        log.info("绑定微信账号请求: userId={}, openid={}, unionid={}, type={}, requestBody={}", 
                 userId, openid, unionid, type, requestBody);
                 
        // 优先使用 JSON 请求体参数，如果为空则使用表单参数
        if (requestBody != null) {
            userId = requestBody.getUserId();
            openid = requestBody.getOpenid();
            unionid = requestBody.getUnionid();
            type = requestBody.getType();
        }
        
        // 参数校验
        if (userId == null || !StringUtils.hasText(openid)) {
            log.error("绑定微信账号失败: 必要参数为空");
            return Result.failed("参数不完整，userId和openid不能为空");
        }
        
        if (!StringUtils.hasText(type)) {
            type = "miniapp"; // 默认为小程序类型
        }
        
        // 调用服务层进行绑定
        try {
            boolean success = userService.bindWechat(userId, openid, unionid, type);
            if (success) {
                log.info("绑定微信账号成功: userId={}, openid={}, type={}", userId, openid, type);
                return Result.success();
            } else {
                log.error("绑定微信账号失败: userId={}, openid={}, type={}", userId, openid, type);
                return Result.failed("绑定微信账号失败");
            }
        } catch (Exception e) {
            log.error("绑定微信账号异常: userId={}, openid={}, type={}, error={}", 
                      userId, openid, type, e.getMessage(), e);
            return Result.failed("绑定微信账号异常: " + e.getMessage());
        }
    }

    /**
     * 解绑微信账号
     */
    @PostMapping("/unbind")
    @Operation(summary = "解绑微信账号", description = "解除用户账号与微信的绑定")
    public Result<Void> unbindWechat(@RequestParam Long userId, @RequestParam String type) {
        try {
            log.info("开始解绑微信账号: userId={}, type={}", userId, type);
            
            // 调用用户服务解绑微信
            boolean success = userService.unbindWechat(userId, type);
            
            if (success) {
                log.info("解绑微信账号成功: userId={}", userId);
                return Result.success();
            } else {
                log.error("解绑微信账号失败: userId={}", userId);
                return Result.failed("解绑微信账号失败");
            }
        } catch (Exception e) {
            log.error("解绑微信账号异常: userId={}, error={}", userId, e.getMessage(), e);
            return Result.failed("解绑微信账号异常: " + e.getMessage());
        }
    }

    /**
     * 获取用户微信绑定状态
     */
    @GetMapping("/status/{userId}")
    @Operation(summary = "获取用户微信绑定状态", description = "获取用户微信绑定状态")
    public Result<Boolean> getWechatBindStatus(@PathVariable Long userId) {
        try {
            boolean isBound = userService.isWechatBound(userId);
            return Result.success(isBound);
        } catch (Exception e) {
            log.error("获取用户微信绑定状态异常: userId={}, error={}", userId, e.getMessage(), e);
            return Result.failed("获取微信绑定状态异常: " + e.getMessage());
        }
    }
} 